What is the using statement used for, explain with example?
What is the using statement used for?
188
19-Jun-2025
ICSM Computer
23-Jun-2025The
usingstatement in C# is used for automatically managing the lifetime of disposable resources—typically unmanaged resources like files, database connections, streams, etc.Purpose:
The
usingstatement ensures that the object’sDispose()method is called automatically, even if an exception occurs. This helps:Syntax:
Applies to:
Any class that implements the
IDisposableinterface, such as:StreamReader,FileStream,SqlConnectionXmlWriter,MemoryStream,HttpClientExample:
C# 8.0+:
In newer versions of C#, you can use a using declaration: